//============================================================================
// Name        : main.cpp
// Author      : Brendon Beebe
//============================================================================

#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include "line.cpp"
#include "main.h"
using namespace std;


bool desc = false; //If true then multiply by -1 (set by -r)
bool caseInsensitive = false; //(set by -i)
bool sortNumber = false;//(set by -n)
int field;
char fileName[1024];



int main(int argc,char *argv[]) {
	parseArguments(argc,argv);
	const int MAX_SIZE = 1048;
	char fileLine[MAX_SIZE];
	line * allLines[1048];
	ifstream file(fileName);
	if(!file.is_open())
		printf("There seems to be a problem loading in the file. (%s)",fileName);

	int i = 0;
	//Save file into heap to prepare for sort
	while (file.getline(fileLine,MAX_SIZE)) {
		//printf("d%s\n",fileLine);
		char * newLine = new char[MAX_SIZE];
		strcpy(newLine,fileLine);
		allLines[i] = new line(newLine,field);
		if(allLines[i]->notEmpty == true)
		    i++;
	}

	//Sort
    qsort(allLines,i,sizeof(line*),compare_Lines);

    //Print out sorted Lines
    for (int j = 0; j < i; j++) {
        std::cout << allLines[j]->originalLine << "\n";
    }
    return 0;
}

int compare_Lines(const void * a, const void * b){
	int result;
	line *arg1 = *(line**) a;
	line *arg2 = *(line**) b;
	if(caseInsensitive){
		int i =0;
		while (arg1->extractedField[i] != '\0'){
			arg1->extractedField[i]=tolower(arg1->extractedField[i]);
			i++;
		}
		i =0;
		while (arg2->extractedField[i] != '\0'){
			arg2->extractedField[i]=tolower(arg2->extractedField[i]);
			i++;
		}
	}
	if(!sortNumber)
		result = strcmp(arg1->extractedField,arg2->extractedField);
	else
		result = atoi(arg1->extractedField) - atoi(arg2->extractedField);

	//Reverse Order if desc
	if(desc)
		result *= -1;

	return result;
}

void parseArguments(int argc,char *argv[]){
	int i;
	for (i =1;i<argc;i++){
		if(*argv[i] == '-'){
			while(*argv[i]!='\0'){
				if(*argv[i]=='i')
					caseInsensitive = true;
				if(*argv[i]=='n')
					sortNumber = true;
				if(*argv[i]=='r')
					desc = true;
				argv[i]++;
			}
		}
		else
			break;
	}
	field = atoi(argv[i++]);
	strcpy(fileName,argv[i]);
}

